package cn.com.taiji.pos.controller;

import cn.com.taiji.model.finals.SessionNames;
import cn.com.taiji.pos.common.util.HttpUtil;
import cn.com.taiji.pos.entity.*;
import cn.com.taiji.pos.service.*;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.dreamyoung.mprelation.AutoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/Order")
public class OrderController {

    @Value("${ACCOUNT_CATEGORY_ID_chuzhi}")
    private String ACCOUNT_CATEGORY_ID_chuzhi;
    @Value("${PROJECT_CODE}")
    private String projectCode;
    @Value("${CREATE_INVENTORY_URL}")
    private String CREATE_INVENTORY_URL;
    @Value("${GET_INVENTORY_URL}")
    private String GET_INVENTORY_URL;
    @Value("${CREATE_OUTSTORE_URL}")
    private String CREATE_OUTSTORE_URL;
    @Autowired
    private ICardInfoService cardInfoService;
    @Autowired
    private AutoMapper autoMapper;
    @Autowired
    private ICardAccountService cardAccountService;
    @Autowired
    private ISystemPosMachineService systemPosMachineService;
    @Autowired
    private ITradeConsumptionMainService tradeConsumptionMainService;
    @Autowired
    private ITradeConsumptionDetailService tradeConsumptionDetailService;
    @Autowired
    private ITradeAccountConsumptionFlowService tradeAccountConsumptionFlowService;
    @Autowired
    private RestTemplate restTemplate;

    /**
     * 获取消费细单
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "GetTradeDetail", method = RequestMethod.POST)
    public String getTradeDetail(Model model, HttpServletRequest request, HttpServletResponse response) {
        String customerId = request.getParameter("customerId");
        String startTime = request.getParameter("startTime");
        String endTime = request.getParameter("endTime");
        List<ItemS> itemsList = new ArrayList<>();
        List<TradeConsumptionMain> mainList = tradeConsumptionMainService.findByCustomerId(customerId, startTime, endTime);
        for (TradeConsumptionMain main : mainList) {
            for (TradeConsumptionDetail detail : tradeConsumptionDetailService.findByMainId(main.getId())) {
                ItemS itemS = new ItemS();
                itemS.setCount(detail.getQuantity());
                itemS.setDateTime(main.getConsumptionTime());
                itemS.setIds(detail.getFoodId());
                itemS.setItem(detail.getFood().getNameZh());
                itemS.setPrice(detail.getPrice().doubleValue());
                itemS.setAmount(detail.getActualAmount().doubleValue());
                itemsList.add(itemS);
            }
        }
        model.addAttribute("result", "success");
        model.addAttribute("itemSList", itemsList);
        return JSONObject.toJSONString(model);
    }


    /**
     * 获取交易主单
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "GetTradeMain", method = RequestMethod.POST)
    public String getTradeMain(Model model, HttpServletRequest request, HttpServletResponse response) {
        String customerId = request.getParameter("customerId");
        String startTime = request.getParameter("startTime");
        String endTime = request.getParameter("endTime");
        SimplePropertyPreFilter filter = new SimplePropertyPreFilter("mainList", "result", "actualAmount", "consumptionTime", "quantity");
        List<TradeConsumptionMain> mainList = tradeConsumptionMainService.findByCustomerId(customerId, startTime, endTime);
        model.addAttribute("result", "success");
        model.addAttribute("mainList", mainList);
        return JSONObject.toJSONString(model, filter);
    }


    /**
     * 获取消费流水单
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "consumptionFlow", method = RequestMethod.POST)
    public String consumptionFlow(Model model, HttpServletRequest request, HttpServletResponse response) {
        String cardCode = request.getParameter("cardCode");
        String physicalCode = request.getParameter("physicalCode");
        CardInfo cardInfo = cardInfoService.findByCardCode(cardCode);
        QueryWrapper<TradeAccountConsumptionFlow> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("CUSTOMER_ID", cardInfo.getCustomerId()).eq("IS_OVER", "1").eq("POS_MACHINE_ID", systemPosMachineService.findByPhysicalCode(physicalCode).getId());
        List<TradeAccountConsumptionFlow> tradeAccountConsumptionFlowList = tradeAccountConsumptionFlowService.list(queryWrapper);
        CardAccount cardAccount = cardAccountService.findCardAccount(cardInfo.getCustomerId(), ACCOUNT_CATEGORY_ID_chuzhi);
        model.addAttribute("result", "success");
        model.addAttribute("flowList", tradeAccountConsumptionFlowList);
        model.addAttribute("balance", cardAccount.getAmount());
        model.addAttribute("cardInfo", autoMapper.mapperEntity(cardInfo));
        return JSONObject.toJSONString(model);
    }

    /**
     * 消费确认
     *
     * @param request
     * @param response
     */
//    @RequestMapping(value = "confirm", method = RequestMethod.POST)
    public String confirm(Model model, HttpServletRequest request, HttpServletResponse response) {
        String id = request.getParameter("id");
        TradeAccountConsumptionFlow tradeAccountConsumptionFlow = tradeAccountConsumptionFlowService.getById(id);
        tradeAccountConsumptionFlow.setIsOver("1");
        tradeAccountConsumptionFlowService.updateById(tradeAccountConsumptionFlow);
        model.addAttribute("result", "success");
        model.addAttribute("message", "确认消费成功");
        return JSONObject.toJSONString(model);
    }

    @GetMapping("/getTodaySalesOrder")
    public String getTodaySalesOrder() {
        HashMap<String, Object> resultMap = new HashMap<>();
        LocalDate searchDate = LocalDate.now();
        resultMap.put("result", "success");

        List<ItemS> createdSalesOrder = tradeConsumptionDetailService.getSalesOrderGroupByFood(searchDate, 1);
        List<ItemS> salesOrder = tradeConsumptionDetailService.getSalesOrderGroupByFood(searchDate, 0);
        createdSalesOrder.addAll(salesOrder);
        resultMap.put("itemsList", createdSalesOrder);
        if (salesOrder.size() > 0) {
            resultMap.put("totalAmount", tradeConsumptionDetailService.getDaySalesTotalAmount(searchDate));
        } else {
            resultMap.put("totalAmount", 0D);
        }
        return JSONObject.toJSONString(resultMap);
    }

    @PostMapping("/sendTodaySalesOrder")
    public String sendTodaySalesOrder(HttpServletRequest request) {
        HashMap<String, Object> resultMap = new HashMap<>();
        SystemAclUser user = (SystemAclUser) WebUtils.getSessionAttribute(request, SessionNames.LOGIN_USER);
        List<ItemS> salesOrder = tradeConsumptionDetailService.getSalesOrderGroupByFood(LocalDate.now(), 0);
        HashMap<String, Object> params = new HashMap<>();
        params.put("itemNumberList", salesOrder);
        params.put("code", projectCode);
        params.put("userName", user.getLoginName());
        return restTemplate.postForObject(CREATE_OUTSTORE_URL, params, String.class);
    }


    @PostMapping("/addInventoryOrder")
    public String createInventoryOrder(@RequestBody Map paramsMap, HttpServletRequest request) {
        SystemAclUser user = (SystemAclUser) WebUtils.getSessionAttribute(request, SessionNames.LOGIN_USER);
        paramsMap.put("code", projectCode);
        paramsMap.put("userName", user.getLoginName());
        return restTemplate.postForObject(CREATE_INVENTORY_URL, paramsMap, String.class);
    }

    @GetMapping("/getInventoryOrder")
    public String getInventoryOrder() {
        //根据扫码查询

        HashMap<String, String> params = new HashMap<>();
        params.put("code", projectCode);
        return HttpUtil.sendToPostWithParameter(GET_INVENTORY_URL, params);
    }


}
